/*
 * @(#)FindWithRegex.java $version 2012. 4. 23.
 *
 * Copyright 2007 NHN Corp. All rights Reserved. 
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package com.etc.regex;

import static org.junit.Assert.*;

import java.io.StringWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.simpleframework.xml.core.Persister;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.etc.regex.data.CopyOfOrchestration;
import com.etc.regex.data.MobileNumberAuthConfirm;
import com.etc.regex.data.MyProfile;
import com.etc.regex.data.Orchestration;

/**
 * @author hs
 */
public class FindWithRegex {

	public void test() {
		String text = "<html><body><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">" + "<html xmlns=\"http://www.w3.org/1999/xhtml\">" + "<head>" + "  <!-- badtag filtered --><meta>" + "  <title>소환알림 메일</title>" + "</head>" + "<body class=\"\">" + "  <div style=\"width:570px;margin:0;padding:0;font-size:12px;font-family:나눔고딕, nanumgothic, 돋움, dotum;color:#333;\">"
			+ "    <table style=\"width:100%;border-collapse:collapse;border-left:1px solid #cdcdcd;border-right:1px solid #cdcdcd;border-bottom:1px solid #f1f1f1;\">" + "      <tr>"
			+ "        <td height=\"41\" style=\"padding:0;background:#8664bf url(http://asset1.me2day.net/images/mail/bg_mail_header.gif) repeat-x left top;vertical-align:middle;border-left:1px solid #8664bf;border-right:1px solid #8664bf;\"><img src=\"http://asset1.me2day.net/images/mail/img_me2logo.gif\" width=\"81\" height=\"41\" alt=\"미투데이\" style=\"margin-left:25px;vertical-align:middle;\" /> "
			+ "          <span style=\"position:relative;top:2px;margin-left:2px;color:#fff;font-size:14px;font-weight:bold;\">소환알림</span>" + "        </td>" + "      </tr>" + "      <tr>" + "        <td style=\"padding:26px 25px 12px;line-height:1.5\">" + "          <a href=\"http://me2day.net/hswon105\" style=\"text-decoration:none;color:#5930bb;\" target=\"_blank\">사랑실천</a>님께서 <strong>소환글</strong>을 작성하셨습니다." + "        </td>" + "      </tr>" + "      <tr>ㅋ"
			+ "        <td style=\"padding:0 25px 0;\">" + "          <table style=\"width:100%;border-collapse:collapse;border-top:1px solid #efefef;\">" + "            <tr>" + "              <td width=\"60\" style=\"padding:20px 0 5px;vertical-align:top;\" rowspan=\"2\"><img src=\"http://static2.me2day.net/images/user/hswon105/profile.png\" width=\"60\" height=\"60\" /></td>"
			+ "              <td style=\"padding:16px 0 5px 15px;line-height:1.5;vertical-align:top;\"> <a href=\"http://me2day.net/me2help\" target=\"_blank\" >미투도우미</a>미투도우미 문의전달 테스트입니다.</td>" + "            </tr>" + "            <tr>" + "              <td style=\"height:30px;padding-left:15px;color:#888;vertical-align:top;\">from <a href=\"http://me2day.net/hswon105\" style=\"text-decoration:none;color:#5930bb;\" target=\"_blank\">사랑실천</a></td>" + "            </tr>" + "          </table>"
			+ "        </td>" + "      </tr>" + "      <tr>" + "        <td style=\"padding:0 25px 15px;\">" + "          <div style=\"padding:7px 10px;border:1px solid #e3dbfe;font-size:11px;background:#f4f3f9;color:#5530bb;line-height:1.5;\">해당 글을 보거나, 사랑실천님의 글에 답변을 남기려면 아래 주소로 이동하세요.<br />"
			+ "            <a target=\"_blank\" href=\"http://me2day.net/hswon105/2012/04/23/pyvppp1-hg7i\" style=\"color:#ae9ee0;font-size:11px;text-decoration:none;font-family:tahoma;\">http://me2day.net/hswon105/2012/04/23/pyvppp1-hg7i</a></div>" + "        </td>" + "      </tr>" + "      <tr>" + "        <td style=\"padding:0 25px 23px;background:url(http://asset1.me2day.net/images/mail/bg_table_bottom_line.gif) repeat-x left bottom;\">"
			+ "          <div style=\"padding-top:11px;border-top:1px solid #efefef;line-height:1.5;\">오늘도 즐거운 하루 보내세요.<br />미투데이 드림</div>" + "        </td>" + "      </tr>" + "    </table>" + "    <p style=\"padding:12px 0 0 25px;margin:0;font-size:11px;color:#666;line-height:1.5;\">      본 메일은 발신전용 입니다. 궁금하신 점이나 불편한 사항은 <a href=\"mailto:help@me2day.net\" style=\"text-decoration:none;color:#5530bb;\">help@me2day.net</a>으로 문의해 주시기 바랍니다.<br />"
			+ "      <span style=\"color:#bbb;font-family:tahoma;\">Copyright &copy; NHN Corp. All Rights Reserved.</span>    </p>" + "  </div>" + "</body>" + "</html><table style='display:none'><tr><td><img src=\"http://owl2.nm.naver.com/received/MTsxMzM1MTQ4ODc3MjY0LjEzODY2LjY3MDU4M0B0dnBsb3dsMjItMi5ubTttZTJoZWxwQG5hdmVyLmNvbQ==.gif\" width=\"0\" height=\"0\" border=\"0\"/></td></tr></table></body></html>	N";
		String regex = ">http://me2day.net/[^/]*/[0-9]{4}/[0-9]{2}/[0-9]{2}/.[^<]*</a>";
		//		String regex = "^*>http://me2day.net/[^/]*/[0-9]{4}/[0-9]{2}/[0-9]{2}/.[^<]*<$*";
		Pattern p = Pattern.compile(regex);
		Matcher matcher = p.matcher(text);

		if (matcher.find()) {
			String subStr = text.substring(matcher.start(), matcher.end());
			String[] split = subStr.split("/");
			System.out.println(split[3]);
		}

	}

	public void splitTest() {
		String content = "";
		String regex = ">http://me2day.net/[^/]*/[0-9]{4}/[0-9]{2}/[0-9]{2}/.[^<]*</a>";
		Pattern p = Pattern.compile(regex);
		Matcher matcher = p.matcher(content);

		if (matcher.find()) {
			String[] splitMeTwoUrl = content.substring(matcher.start(), matcher.end()).split("/");

		}

	}

	public void test2() {
		final String PARENT_TAG_DATA_START = "<data>";
		final String PARENT_TAG_DATA_END = "</data>";
		String responseStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><rsp><result><stat>ok</stat><code>200</code><desc /></result><data>		<rsp><result><stat>ok</stat><code>200</code><desc /></result><data><userId> 1000135638102241110002</userId><userNick>Father</userNick><userAccount>user@samsung.com</userAccount><internationalCode>82</internationalCode><userPhoneNumber>1234567</userPhoneNumber></data></rsp><rsp><result><stat>ok</stat><code>200</code><desc /></result><data><groupCount>1</groupCount><group><groupId>2000135638102241110002</groupId><groupName>Hong</groupName><userStatus>member</userStatus><groupStatus>activate</groupStatus><groupRestore>no</groupRestore><groupExpiredDate>none</groupExpiredDate><groupRegisteredTime>2011-08-26 16:00:00</groupRegisteredTime></group></data></rsp></data></rsp>";
		String regex = "<data>(\\s*<rsp>.*</rsp>\\s*)</data>";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(responseStr);
		String subStr = null;
		if (matcher.find()) {
			subStr = matcher.group(1);
		}

		subStr = subStr.replaceAll("</rsp>\\s*<rsp>", "</rsp>@@@###%%%<rsp>");
		String[] subStrArray = subStr.split("@@@###%%%");

		System.err.println(subStrArray[0]);
		System.err.println(subStrArray[1]);
	}

	public void test3() throws Exception {
		final String RESPONSE_DATA_BODY = "<data>(\\s*<rsp>.*</rsp>\\s*)</data>";
		final int RESPONSE_DATA_BODY_PART = 1;

		Class<?> clazz = Orchestration.class;

		List<Class<?>> classList = new ArrayList<Class<?>>();
		classList.add(MyProfile.class);
		classList.add(MobileNumberAuthConfirm.class);

		//		Object[] responseResult = new Object[classList.size()];
		List<Object> dataList = new ArrayList<Object>();
		Object result = clazz.newInstance();

		String responseStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<rsp>\r\n\t<result>\r\n\t\t<stat>ok</stat>\r\n\t\t<code>200</code>\r\n\t\t<desc />\r\n\t</result>\r\n\t<data>\r\n\t\t<rsp>\r\n\t\t\t<result>\r\n\t\t\t\t<stat>ok</stat>\r\n\t\t\t\t<code>200</code>\r\n\t\t\t</result>\r\n\t\t\t<data />\r\n\t\t</rsp>\r\n\t\t<rsp>\r\n\t\t\t<result>\r\n\t\t\t\t<stat>ok</stat>\r\n\t\t\t\t<code>200</code>\r\n\t\t\t\t<desc />\r\n\t\t\t</result>\r\n\t\t\t<data>\r\n\t\t\t\t<scheduleId>5005135637951044810000</scheduleId>\r\n\t\t\t</data>\r\n\t\t</rsp>\r\n\t</data>\r\n</rsp>";
		//		String responseStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<rsp>\r\n\t<result>\r\n\t\t<stat>ok</stat>\r\n\t\t<code>200</code>\r\n\t\t<desc />\r\n\t</result>\r\n\t<data>\r\n\r\n\r\n\ta<></data>\r\n</rsp>";
		Pattern pattern = Pattern.compile("<data>(?:\r\n|[\r\n])*\t*.*<rsp>(?:\r\n|[\r\n])*\t*.*</rsp>(?:\r\n|[\r\n])*\t*.*</data>");
		Matcher matcher = pattern.matcher(responseStr);
		String subStr = null;
		if (matcher.find()) {
			subStr = matcher.group(RESPONSE_DATA_BODY_PART);
		} else {
			fail();
		}

		subStr = subStr.replaceAll("</rsp>\\s*<rsp>", "</rsp>@@@###%%%<rsp>");
		String[] subStrArray = subStr.split("@@@###%%%");

		// split된 각각의 문자열을 simple xml을 이용해 객체로 변환

		if (subStrArray.length != classList.size()) {
			//TODO 요청한 INTERFACE 개수와 결과 개수가 동일하지 않으므로 오류상황
		}

		Persister persister = new Persister();
		for (int index = 0; index < subStrArray.length; index++) {
			dataList.add(persister.read(classList.get(index), subStrArray[index], false));
		}

		Method method = clazz.getDeclaredMethod("setDataList", List.class);
		method.setAccessible(true);
		method.invoke(result, dataList);

		Orchestration orchestration = (Orchestration)result;
	}

	public void test4() throws Exception {
		String responseStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<rsp>\r\n\t<result>\r\n\t\t<stat>ok</stat>\r\n\t\t<code>200</code>\r\n\t\t<desc />\r\n\t</result>\r\n\t<data><![CDATA[\r\n\t\t<rsp>\r\n\t\t</rsp>\r\n\t\t]]></data>\r\n</rsp>";
		Persister persister = new Persister();
		Object result = persister.read(Orchestration.class, responseStr, false);
		Orchestration orchestration = (Orchestration)result;

	}

	public void test5() throws Exception {
		String responseStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><rsp><result><stat>ok</stat><code>200</code><desc /></result><data><rsp><result><stat>ok</stat><code>200</code><desc /></result><data><userId>1000000000000000000278</userId><accountId>user20@samsung.com</accountId><userNick>SVR Father</userNick><internationalCode>82</internationalCode><userTel>01022223333</userTel><birthDate>1990-01-31</birthDate><thumbnail>encoded_thumbnail_full_url</thumbnail><profileUpdateCheck>yes</profileUpdateCheck><mobileAuthCheck>yes</mobileAuthCheck><mobileAuthFail>no</mobileAuthFail><jabberId>abc@ejabberd.auth</jabberId><xmppPassword>1u2he83</xmppPassword></data></rsp><rsp><result><stat>fail</stat><code>3001</code><desc>Access Denied - Invalid Auth code</desc></result><data><codeGenCnt>1</codeGenCnt><authFailCnt>2</authFailCnt></data></rsp></data></rsp>";

		Persister persister = new Persister();
		Orchestration orchestration = persister.read(Orchestration.class, responseStr, false);

	}

	public void test6() throws Exception {
		String responseStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><rsp><aaa key=\"a\">a</aaa><aaa key=\"b\">b</aaa></rsp>";

		Persister persister = new Persister();
		CopyOfOrchestration orchestration = persister.read(CopyOfOrchestration.class, responseStr, false);
	}

	@Test
	public void test8() throws Exception {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = builder.parse("http://10.67.8.90:8080/familystory/service/familystory/v2/orchestration/get");

		TransformerFactory tFactory = TransformerFactory.newInstance();
		Transformer transformer = tFactory.newTransformer();
		transformer.setOutputProperty(OutputKeys.INDENT, "no");
		transformer.setOutputProperty(OutputKeys.METHOD, "xml");
		transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");

		NodeList nodeList = doc.getDocumentElement().getChildNodes();
		DOMSource source = null;
		StringWriter stringWriter = null;
		StreamResult result = null;

		for (int nodeIndex = 0; nodeIndex < nodeList.getLength(); nodeIndex++) {
			Node node = nodeList.item(nodeIndex);
			if (node instanceof Element && StringUtils.equals(node.getNodeName(), "data")) {
				NodeList dataNodeList = node.getChildNodes();
				for (int dataIndex = 0; dataIndex < dataNodeList.getLength(); dataIndex++) {
					Node rspNode = dataNodeList.item(dataIndex);
					if (rspNode instanceof Element && StringUtils.equals(rspNode.getNodeName(), "rsp")) {
						stringWriter = new StringWriter();
						result = new StreamResult(stringWriter);
						source = new DOMSource(rspNode);
						transformer.transform(source, result);
						System.err.println(stringWriter.toString());
					}
				}
				break;
			}
		}
	}
}
